package com.example.demo.generator.config;

import com.example.demo.generator.util.JwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.configurationprocessor.json.JSONObject;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

public class tokenInterceptor implements HandlerInterceptor {

    @Autowired
    public JwtUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //return false;
        Map<String, String> map = new HashMap<>();
        String token = request.getHeader("token");
        if (StringUtils.isNotBlank(token)) {
            int verify = jwtUtil.verify(token);
            if (verify == 1) {
                return true;
            } else {
                //验证失败
                if (verify == 2) {
                    map.put("errorMsg", "token已过期");
                } else if (verify == 0) {
                    map.put("errorMsg", "用户信息验证失败");
                }
                JSONObject jsonObject = new JSONObject(map);
                response.setContentType("application/json");
                //设置响应的编码
                response.setCharacterEncoding("utf-8");
                //响应
                PrintWriter pw = response.getWriter();
                pw.write(jsonObject.toString());
                pw.flush();
                pw.close();
                return false;
            }
        } else {
            map.put("errorMsg", "未携带token信息");
            JSONObject jsonObject = new JSONObject(map);
            response.setContentType("application/json");
            //设置响应的编码
            response.setCharacterEncoding("utf-8");
            //响应
            PrintWriter pw = response.getWriter();
            pw.write(jsonObject.toString());
            pw.flush();
            pw.close();
            return false;
        }

    }
}
